"""
加密工具模块
提供公共参数的加密和解密功能
"""
import base64
import os
import logging
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

logger = logging.getLogger(__name__)


class CryptoManager:
    """加密管理器"""
    
    def __init__(self, secret_key=None):
        """
        初始化加密管理器
        
        Args:
            secret_key: 加密密钥，如果为None则从环境变量获取
        """
        if secret_key is None:
            # 使用与executor模块相同的环境变量和默认值
            secret_key = os.environ.get('CRYPTO_SECRET_KEY', 'default-secret-key-change-in-production')
        
        self.secret_key = secret_key.encode()
        self._fernet = None
    
    def _get_fernet(self):
        """获取Fernet实例"""
        if self._fernet is None:
            # 使用与executor模块相同的盐值，确保一致性
            salt = b'stable_salt_for_global_params'  # 与executor模块保持一致
            kdf = PBKDF2HMAC(
                algorithm=hashes.SHA256(),
                length=32,
                salt=salt,
                iterations=100000,
            )
            key = base64.urlsafe_b64encode(kdf.derive(self.secret_key))
            self._fernet = Fernet(key)
        return self._fernet
    
    def encrypt(self, plaintext):
        """
        加密文本
        
        Args:
            plaintext: 要加密的明文
            
        Returns:
            str: 加密后的密文（base64编码）
        """
        try:
            if not plaintext:
                return plaintext
            
            fernet = self._get_fernet()
            encrypted_data = fernet.encrypt(plaintext.encode('utf-8'))
            return base64.urlsafe_b64encode(encrypted_data).decode('utf-8')
        except Exception as e:
            logger.error(f"加密失败: {e}")
            raise
    
    def decrypt(self, ciphertext):
        """
        解密文本
        
        Args:
            ciphertext: 要解密的密文（base64编码）
            
        Returns:
            str: 解密后的明文
        """
        try:
            if not ciphertext:
                return ciphertext
            
            fernet = self._get_fernet()
            encrypted_data = base64.urlsafe_b64decode(ciphertext.encode('utf-8'))
            decrypted_data = fernet.decrypt(encrypted_data)
            return decrypted_data.decode('utf-8')
        except Exception as e:
            logger.error(f"解密失败: {e}")
            raise


# 全局加密管理器实例
_crypto_manager = None


def get_crypto_manager():
    """获取全局加密管理器实例"""
    global _crypto_manager
    if _crypto_manager is None:
        _crypto_manager = CryptoManager()
    return _crypto_manager


def encrypt_value(value):
    """加密值"""
    return get_crypto_manager().encrypt(value)


def decrypt_value(encrypted_value):
    """解密值"""
    return get_crypto_manager().decrypt(encrypted_value)